package com.bigdatastudio.monitor.Elasticsearch;

import com.bigdatastudio.common.Utils.R;
import com.bigdatastudio.monitor.SearchVo.SearchNoticeVo;
import com.bigdatastudio.monitor.SearchVo.SearchParm;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiao_jie
 * @date 2022/11/8 16:58
 * @describe 全局搜索接口
 */

@RestController
public class ElasticsearchController {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @PostMapping("/monitor/search")
    public R search(@RequestBody SearchParm searchParm) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        List<QueryBuilder> listQuery = new ArrayList<>();
        listQuery.add(QueryBuilders.matchQuery("noticeTitle",searchParm.getSearchText()));
        listQuery.add(QueryBuilders.matchQuery("noticeAbstract",searchParm.getSearchText()));
        boolQueryBuilder.should().addAll(listQuery);
        NativeSearchQuery nativeSearchQuery = new NativeSearchQuery(boolQueryBuilder);
        SearchHits<SearchNoticeVo> searchHits = elasticsearchRestTemplate.search(nativeSearchQuery, SearchNoticeVo.class);
        List<SearchHit<SearchNoticeVo>> hits = searchHits.getSearchHits();
        List<SearchNoticeVo> list = new ArrayList<>();
        hits.forEach(sh -> {
            list.add(sh.getContent());
        });
        return R.ok(list,"搜索成功");
    }

}
